package ph.com.gs3.formalistics.model.facades;

import org.json.JSONException;
import org.json.JSONObject;

import ph.com.gs3.formalistics.global.constants.StarMark;
import ph.com.gs3.formalistics.model.ldao.DocumentsLDAO;
import ph.com.gs3.formalistics.model.ldao.UserDocumentsLDAO;
import ph.com.gs3.formalistics.model.vo.business.User;
import ph.com.gs3.formalistics.model.vo.business.document.Document;
import ph.com.gs3.formalistics.model.vo.business.form.Form;
import android.content.Context;

public class DocumentsDataWriter {

	protected User user;
	protected DocumentsLDAO documentsLDAO;
	protected UserDocumentsLDAO userDocumentsLDAO;

	public DocumentsDataWriter(Context context, User user) {

		this.user = user;
		documentsLDAO = new DocumentsLDAO(context);
		userDocumentsLDAO = new UserDocumentsLDAO(context);
	}

	public void changeDocumentStarMark(int documentId, StarMark starMark) {

		try {
			userDocumentsLDAO.open();
			userDocumentsLDAO.changeDocumentStarMark(documentId, starMark);
		} finally {
			userDocumentsLDAO.close();
		}

		// Check for outgoing action about this star mark

	}

	/**
	 * Saves or updates a document passed to this method. If the document is not yet
	 * existing, a new one is saved along with its field values in its corresponding form
	 * fields table, otherwise, the existing record and its form field values are updated.
	 * 
	 * @param document
	 *            The document to save or update.
	 * @param form
	 *            The form of the document to save or update.
	 * @return The updated document instance that contains the new data and form fields
	 *         data.
	 */
	public Document updateOrSaveDocument(Document document, Form form) {

		String webId = document.getWebId();
		int formId = document.getFormId();

		Document existingDocument = null;
		Document savedDocument = null;
		JSONObject savedFieldValues = null;

		String formTableName = form.getGeneratedFormTableName();

		documentsLDAO.open();

		try {
			existingDocument = documentsLDAO.getDocument(webId, formId, user.getId());

			if (existingDocument == null) {
				savedDocument = documentsLDAO.saveDocument(document);
				savedFieldValues = documentsLDAO.insertDocumentFieldValues(savedDocument.getId(),
				        formTableName, savedDocument.getFieldValuesJSON(), form.getActiveFields());
			} else {
				savedDocument = documentsLDAO.updateDocument(document, user.getId());
				savedFieldValues = documentsLDAO.updateDocumentFieldValues(savedDocument.getId(),
				        formTableName, savedDocument.getFieldValuesJSON(), form.getActiveFields());
			}

			savedDocument.setFieldValuesJSON(savedFieldValues);
			insertUserDocument(savedDocument, document);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			documentsLDAO.close();
		}

		return savedDocument;
	}

	public void insertUserDocument(Document savedDocument, Document originalDocument) {
		userDocumentsLDAO.open();

		int originalUserId = userDocumentsLDAO.getUserOfDocument(savedDocument.getId());
		if (originalUserId != user.getId()) {
			userDocumentsLDAO.insertUserDocument(user.getId(), savedDocument.getId(),
			        originalDocument.getStarMark());
		}

		userDocumentsLDAO.close();
	}
}
